package com.atguigu.schedule.DAO.impl;

import com.atguigu.schedule.DAO.BaseDAO;
import com.atguigu.schedule.DAO.SysUserDAO;
import com.atguigu.schedule.pojo.SysUser;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;

public class SysUserDAOImpl extends BaseDAO<SysUser> implements SysUserDAO {
    @Override
    public int insert(Connection conn, SysUser user) {
        String sql = "insert into sys_user(username, user_pwd) values(?,?)";
        return update(conn, sql, user.getUserName(), user.getUserPwd());
    }

    @Override
    public void deleteById(Connection conn, int id) {
        String sql = "delete from sys_user where uid = ?";
        update(conn, sql, id);
    }

    @Override
    public void update(Connection conn, SysUser user) {
        String sql = "update sys_user set username=?, user_pwd=? where uid = ?";
        update(conn, sql, user.getUserName(), user.getUserPwd(), user.getUid());
    }

    @Override
    public SysUser getUserById(Connection conn, int id) {
        String sql = "select uid, username AS userName, user_pwd AS userPwd from sys_user where uid = ?";
        ArrayList<SysUser> users = query(conn, sql, id);
        if (!users.isEmpty()) {
            return users.get(0);
        }
        return null;
    }

    @Override
    public List<SysUser> getUsers(Connection conn) {
        String sql = "select uid, username AS userName, user_pwd AS userPwd from sys_user";
        return query(conn, sql);
    }

    @Override
    public long getUserCount(Connection conn) {
        String sql = "select count(*) from sys_user";
        return getValue(conn, sql);
    }

    @Override
    public long getUserCountWithName(Connection conn, String name) {
        String sql = "select count(*) from sys_user where username = ?";
        return getValue(conn, sql, name);
    }

    @Override
    public SysUser getUserByName(Connection conn, String name) {
        String sql = "select uid, username AS userName, user_pwd AS userPwd from sys_user where username = ?";
        ArrayList<SysUser> users = query(conn, sql,name);
        if (!users.isEmpty()) {
            return users.get(0);
        }
        return null;
    }
}
